import sys
import os
import time
import xlrd
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QVBoxLayout,
                           QHBoxLayout, QWidget, QLabel, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QFont

class LoadingThread(QThread):
    finished = pyqtSignal()
    error = pyqtSignal(str)

    def __init__(self, file_path, dir_path):
        super().__init__()
        self.file_path = file_path
        self.dir_path = dir_path

    def run(self):
        try:
            # 创建并进入一级文件夹--人工智能学院
            college_dir = os.path.join(self.dir_path, '人工智能学院')
            if not os.path.exists(college_dir):
                os.mkdir(college_dir)

            # 读取excel
            data = xlrd.open_workbook(self.file_path)
            sheet1 = data.sheets()[0]
            row = sheet1.nrows

            for i in range(row):
                if i == 0:  # 跳过第一行
                    continue
                
                rowdate = sheet1.row_values(i)
                class_dir = os.path.join(college_dir, rowdate[0])
                
                if not os.path.exists(class_dir):
                    # 创建班级文件夹
                    os.mkdir(class_dir)
                    
                    # 创建三个子文件夹
                    folders = ['毕业生登记表', '毕业证扫描件', '高中学籍档案']
                    for folder in folders:
                        subfolder_path = os.path.join(class_dir, folder)
                        os.mkdir(subfolder_path)
                        
                        # 在每个子文件夹中创建学生文件夹
                        for k in range(row):
                            rowData = sheet1.row_values(k)
                            if rowData[0] == rowdate[0]:  # 如果是同一个班级
                                student_folder = str(rowData[1]) + rowData[2]  # 学号 + 姓名
                                student_path = os.path.join(subfolder_path, student_folder)
                                os.mkdir(student_path)

            self.finished.emit()
            
        except Exception as e:
            self.error.emit(str(e))

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.uploaded_file = None
        self.dir_path = None
        self.file_name = None

    def initUI(self):
        # 设置窗口标题和大小
        self.setWindowTitle('学生文件夹创建工具')
        self.setFixedSize(500, 300)

        # 创建中央部件和主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(30, 30, 30, 30)

        # 创建标题标签
        title_label = QLabel('学生文件夹创建工具')
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setFont(QFont('Arial', 16, QFont.Bold))
        main_layout.addWidget(title_label)

        # 创建按钮
        download_btn = QPushButton('下载模板')
        download_btn.setFixedHeight(40)
        download_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)

        upload_btn = QPushButton('上传文件')
        upload_btn.setFixedHeight(40)
        upload_btn.setStyleSheet("""
            QPushButton {
                background-color: #008CBA;
                color: white;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #007399;
            }
        """)

        create_btn = QPushButton('创建文件夹')
        create_btn.setFixedHeight(40)
        create_btn.setStyleSheet("""
            QPushButton {
                background-color: #f44336;
                color: white;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #da190b;
            }
        """)

        # 创建文件名显示标签
        self.file_label = QLabel('未选择文件')
        self.file_label.setAlignment(Qt.AlignCenter)
        self.file_label.setStyleSheet("""
            QLabel {
                background-color: #f8f9fa;
                padding: 10px;
                border-radius: 5px;
                border: 1px solid #dee2e6;
            }
        """)

        # 创建水平布局来放置下载和上传按钮
        button_layout = QHBoxLayout()
        button_layout.addWidget(download_btn)
        button_layout.addWidget(upload_btn)
        
        # 添加所有组件到主布局
        main_layout.addLayout(button_layout)
        main_layout.addWidget(self.file_label)
        main_layout.addWidget(create_btn)

        # 连接按钮信号
        download_btn.clicked.connect(self.download_template)
        upload_btn.clicked.connect(self.upload_file)
        create_btn.clicked.connect(self.create_folder)

        # 初始化加载线程变量
        self.loading_thread = None

    def download_template(self):
        # 模板文件路径
        template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "人工智能学院.xls")
        
        # 检查模板文件是否存在
        if not os.path.exists(template_path):
            QMessageBox.warning(self, "错误", "模板文件不存在！请确保'人工智能学院.xls'文件在程序同目录下。")
            return
            
        # 选择保存模板的位置
        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "保存模板文件",
            "人工智能学院.xls",
            "Excel Files (*.xls);;All Files (*)"
        )
        
        if file_path:
            try:
                # 复制模板文件到选择的位置
                import shutil
                shutil.copy2(template_path, file_path)
                QMessageBox.information(self, "成功", "模板已成功下载到选择的位置！")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"下载模板时出错：{str(e)}")

    def upload_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择文件",
            "",
            "Excel Files (*.xls);;All Files (*)"
        )
        if file_path:
            self.uploaded_file = file_path
            self.dir_path = os.path.dirname(file_path)  # 获取文件所在目录
            self.file_name = os.path.basename(file_path)  # 使用os.path.basename获取文件名
            self.file_label.setText(f'已选择文件: {self.file_name}')

    def create_folder(self):
        if not self.uploaded_file:
            QMessageBox.warning(self, "警告", "请先上传文件")
            return

        # 显示加载对话框
        self.loading_dialog = QMessageBox(self)
        self.loading_dialog.setWindowTitle("处理中")
        self.loading_dialog.setText("正在创建文件夹，请稍候...")
        self.loading_dialog.setStandardButtons(QMessageBox.NoButton)
        self.loading_dialog.show()

        # 创建并启动加载线程
        self.loading_thread = LoadingThread(self.uploaded_file, self.dir_path)
        self.loading_thread.finished.connect(self.on_folder_created)
        self.loading_thread.error.connect(self.on_folder_error)
        self.loading_thread.start()



    def on_folder_created(self):
        # 确保加载对话框被正确关闭
        if hasattr(self, 'loading_dialog') and self.loading_dialog:
            self.loading_dialog.done(0)  # 使用done而不是close来确保对话框被完全关闭
            self.loading_dialog = None
            
        # 显示完成消息
        QMessageBox.information(self, "完成", "创建完成，请在文件同目录下查看。")
        
    def on_folder_error(self, error_msg):
        # 确保加载对话框被正确关闭
        if hasattr(self, 'loading_dialog') and self.loading_dialog:
            self.loading_dialog.done(0)
            self.loading_dialog = None
            
        # 显示错误消息
        QMessageBox.critical(self, "错误", f"创建文件夹时出错：{error_msg}")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
